<template>
  <UploadExcel :on-success="handleSuccess" :before-upload="beforeUpload" />
</template>

<script>
import { formatExcelDate } from '@/utils/index'
import { addEmployees } from '@/api/employees'
export default {
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    // 上传前判断大小
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    // 将上传的eccal内容，转为js对象
    handleSuccess({ results, header }) {
      this.tableData = results
      this.tableHeader = header
      // 格式化，把中文转为英文
      const res = this.transExcel(results)
      //   console.log('res', res)
      //   console.log('header', header)
      // 发送ajax
      this.getaddEmployees(res)
    },
    // 格式化数据
    transExcel(data) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      return data.map(zhObj => {
        // 声明空对象
        const enObj = {}
        // 得到中文键的数组
        const zhKeys = Object.keys(zhObj) // ['姓名', '手机号']
        // 遍历数组
        zhKeys.forEach(zhKey => {
          // 根据映射关系，中文键转为英文键
          const enKey = mapInfo[zhKey]
          // 给键加值
          // 时间格式化 把excel的时间还原
          if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            enObj[enKey] = formatExcelDate(zhObj[zhKey])
          } else {
            enObj[enKey] = zhObj[zhKey]
          }
        })
        return enObj
      })
    },
    // 批量导入数据
    async getaddEmployees(data) {
      try {
        const res = await addEmployees(data)
        // console.log('addEmployees', res)
        this.$message.success(res.data.message)
        // 数据导入成功，回到原来的页面
        this.$router.back()
        // 保存数据
      } catch (err) {
        console.log('addEmployees', err)
      }
    }
  }
}
</script>

<style>

</style>
